import axios from 'axios';

export const downloadFile = (method, url, data, { fileName } = {}) => {
  return axios({
    url,
    data,
    method: method,
    responseType: 'blob'
  })
    .then(res => {
      const blob = res.data;
      const url = window.URL.createObjectURL(blob);
      const filename =
        fileName ||
        decodeURI(res.headers['content-disposition'].replace(/attachment; filename="|"/g, ''));

      let el = document.createElement('a');
      el.href = url;
      el.download = filename;
      el.hidden = true;

      document.body.appendChild(el);
      el.click();
      document.body.removeChild(el);
    })
    .catch(error => {
      window.console.log(error);
    });
};
